<template>
  <!--附件弹窗部分 -->
  <el-form
    v-loading="previewloading"
    class="dialog-backgroundcolor"
  >
    <div style="float:right;margin-top:10px">
      <el-upload :show-file-list="showFileList" class="upload-demo" accept=".pdf" action="#" multiple :file-list="fileList" :http-request="make_tmp_list">
        <el-button v-if="display" size="small" type="primary">上传附件</el-button>
      </el-upload>
    </div>
    <!--    <h3>待上传附件：</h3>-->
    <!--    <el-table :data="tmp_List" stripe :header-cell-style="{background:'#eef1f6',color:'#606266'}" style="width: 100%">-->
    <!--      <template slot="empty">-->
    <!--        <tableEmpty />-->
    <!--      </template>-->
    <!--      <el-table-column type="index" label="序号" width="180" />-->
    <!--      <el-table-column prop="fileName" label="文件" />-->
    <!--      <el-table-column label="操作" width="120">-->
    <!--        <template slot-scope="row">-->
    <!--          <el-button v-if="display" type="text" size="small" @click="tmp_deleteFile(row)">删除</el-button>-->
    <!--        </template>-->
    <!--      </el-table-column>-->
    <!--    </el-table>-->
    <!--    <h3>已有附件：</h3>-->
    <el-table ref="fileTable" v-loading="fileTableloading" :data="table_list" stripe :header-cell-style="{background:'#eef1f6',color:'#606266'}" style="width: 100%">
      <template slot="empty">
        <tableEmpty />
      </template>
      <el-table-column type="index" label="序号" width="180" />
      <el-table-column prop="fileName" label="文件" />
      <el-table-column label="操作" width="120">
        <template slot-scope="row">
          <el-button v-if="!row.row.jia" type="text" size="small" @click="preview(row)">预览</el-button>
          <el-button v-if="!row.row.jia" type="text" size="small" @click="downFile(row)">下载</el-button>
          <el-button v-if="display" type="text" size="small" @click="!row.row.jia ? deleteFile(row) : tmp_deleteFile(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    <el-row>-->
    <!--      <el-col-->
    <!--        :span="24"-->
    <!--        style="text-align: center; margin-top:20px;"-->
    <!--      >-->
    <!--        <el-button @click="notshow">-->
    <!--          关闭-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--    </el-row>-->
  </el-form>
</template>
<script>
import tableEmpty from '@/components/table/empty'
import {
  Upload,
  attachmentPreservation,
  insertFileInfoList,
  attachmentDownload,
  attachmentDelete
} from '@/api/baseInfo'
export default {
  components: { tableEmpty },
  props: ['middleTableCode'],
  data() {
    return {
      Name: '姓名',
      display: true,
      showappendix: false,
      // Table laoding刷新
      fileTableloading: false,
      // 全部 loading刷新
      previewloading: false,
      fileList: [],
      tableData: [],
      dialogStatus: '',
      allowFiles:'.pdf.PDF',
      savedata: {
        agencyId: null,
        billguid: '',
        fileId: '',
        fileName: '',
        middleTableCode: '',
        operateType: '',
        children: []
      },
      savedata_list: [],
      downLoadlist: {
        appid: 'salary',
        fileguid: ''
      },
      showFileList: false,
      List: [],
      OperateList:[],
      tmp_List: [], // 纯显示list
      tmp_id: null,
      tmp_agencyId: null
    }
  },
  computed: {
    table_list() {
      return [...this.List, ...this.tmp_List]
    }
  },
  watch: {},
  mounted() {},
  created() {},
  methods: {
    notshow() {
      this.showappendix = false
    },
    clear_tmp_list(id, agencyId) {
      this.tmp_List = []
      this.savedata_list = []
      this.tmp_id = id
      this.tmp_agencyId = agencyId
      this.attachmentPreservation(id, agencyId)
    },
    make_tmp_list(item) {
      let that=this
      item.fileName = item.file.name
       let arr= item.file.name.split('.')
     let extension=arr[arr.length-1]
    //  if(this.allowFiles.indexOf(extension)<0){
    //    this.$message({
    //         showClose: true,
    //         message: '不允许的文件类型！',
    //         type: 'warning',
    //         duration: 4000
    //       })
    //    return 
    //   }
    for(let i=0;i<this.tmp_List.length;i++){
      if(that.tmp_List[i].fileName===item.fileName){
            this.$message({
             showClose: true,
             message: "附件已上传过"+item.fileName,
             type: 'warning',
             duration: 4000
           })
             this.fileTableloading = false
              // this.Operate()
            return 
      }
    }
    for(let i=0;i<this.List.length;i++){
      if(that.List[i].fileName===item.fileName){
            this.$message({
             showClose: true,
             message: "附件已上传过"+item.fileName,
             type: 'warning',
             duration: 4000
           })
             this.fileTableloading = false
              // this.Operate()
            return 
      }
    }
    
      item.jia = true
      this.tmp_List.push(item)
    },
    get_tmp_list() {
      return new Promise(resolve => {
        resolve(this.tmp_List)
      })
    },
   
    // 上传文件
    uploadExcel(item, length, num) {
      const Lists=this.OperateList
      return new Promise(resolve => {
        const fileObj = item.file
        // FormData 对象
        const form = new FormData()
        // 文件对象
        const uuid = this.uuid()
      form.append('filename', fileObj.name)
      form.append('file', fileObj)
      form.append('doctype', '')
      form.append('year', this.$store.getters.userInfo.year)
      form.append('userguid', this.$store.getters.userInfo.userguid)
      form.append('appid', 'salary')
      form.append('province', this.$store.getters.userInfo.province)
      form.append('billguid', uuid)
        this.fileTableloading = true
        this.List.splice(0, this.List.length)
        Upload(form).then(response => {
          if (response.rscode === '100000') {
            this.savedata.billguid = uuid
            this.savedata.middleTableCode = this.middleTableCode
            this.savedata.fileId = response.data
            this.savedata.fileName = fileObj.name
          for(let i=0;i<Lists.length;i++){
            if(Lists[i].fileName===fileObj.name){
             this.$message({
             showClose: true,
             message: "上传失败  "+Lists[i].middleTableCode+"附件已上传过"+Lists[i].fileName,
             type: 'warning',
             duration: 4000
           })
             this.fileTableloading = false
              // this.Operate()
            return 
      }
    }
            this.savedata.agencyId = this.tmp_agencyId
            this.savedata.children.push(this.tmp_id)
            this.savedata_list.push(this.savedata)
            num++
            if (num === length) {
              resolve(num)
            }
          } else if (response.rscode === '119000') {
            this.$message({
              showClose: true,
              message: '上传失败',
              type: 'error',
              duration: 0
            })
          }
        })
      })
    },
    // 批量附件保存
    save() {
      return new Promise(reslove => {
        let num
      this.tmp_List.forEach(async item => {
        num = await this.uploadExcel(item, this.tmp_List.length, 0)
        if (num === this.tmp_List.length) {
          insertFileInfoList(this.savedata_list).then(response => {
            if (response.data === '100000') {
              this.$message({
                showClose: true,
                message: '上传附件成功',
                type: 'success',
                duration: 4000
              })
              this.fileTableloading = false
              this.attachmentPreservation(this.tmp_id, this.tmp_agencyId)
              reslove(true)
            } else{
              reslove(false)
            }
          })
        }
      })
      })
    },
    // 附件查询
    attachmentPreservation(id, agencyId, operateType) {
      return new Promise(resolve => {
        const ids = []
         ids.push(id)
        const params = {
          'list': ids,
          'agencyId': agencyId,
          'operateType': operateType || 2
        }
        attachmentPreservation(params).then(response => {
          this.List = response.data
          this.fileTableloading = false
          resolve(this.List)
        })
      })
    },
    tmp_deleteFile(row) {
      this.tmp_List.splice(this.List.length - row.$index, 1)
    },
    // 下载附件
    downFile(row) {
      this.previewloading = true
      this.downLoadlist.fileguid = row.row.fileId
      // 文件对象
      attachmentDownload(this.downLoadlist).then(response => {
        const link = document.createElement('a')
        const objectUrl = URL.createObjectURL(response)
        link.href = objectUrl
        link.download = row.row.fileName
        link.click()
        URL.revokeObjectURL(objectUrl)
        this.previewloading = false
      })
    },
    // 附件删除
    deleteFile(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.previewloading = true
        attachmentDelete(row.row).then(response => {
          if (response.data === '100000') {
            this.$message({
              showClose: true,
              message: '删除成功',
              type: 'success',
              duration: 4000
            })
            this.previewloading = false
            this.attachmentPreservation(this.tmp_id, this.tmp_agencyId)
          }
        })
      })
    },
    // 附件预览
    preview(row) {
      this.previewloading = true

      this.downLoadlist.fileguid = row.row.fileId
      // 文件对象
      attachmentDownload(this.downLoadlist).then(response => {
        const binaryData = []
        binaryData.push(response)
        // 获取blob链接
        const pdfUrl = window.URL.createObjectURL(
          new Blob(binaryData, { type: 'application/pdf' })
        )
        window.open(pdfUrl)
        this.previewloading = false
      })
    },
    // 生成uuid
    uuid() {
      var s = []
      var hexDigits = '0123456789abcdef'
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
      }
      s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = ''

      var uuid = s.join('')
      return uuid
    }
  }
}
</script>
